package com.ken.callblock2.listener;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import ken.app.helper.Helper;

import com.android.internal.telephony.ITelephony;
import com.ken.callblock2.CallBlock2;
import com.ken.callblock2.R;
import com.ken.callblock2.activity.MainActivity;
import com.ken.callblock2.tools.KENLog;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneCallListener extends PhoneStateListener {
	
	private TelephonyManager 	mTelephonyManager;
	private NotificationManager mNotificationManager;
	private AudioManager		mAudioManager;
	private Context 			mContext ;
	private int					TemporaryRingMode;
	
	public static int RINGER_MODE_EndCall 			= 99;
	public static int RINGER_MODE_Vibrate 			= 98;
	public static int RINGER_MODE_Silent 			= 97;
	
	public PhoneCallListener(Context context){
		mContext 				= context;
		mTelephonyManager 		= (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		mNotificationManager	= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		mAudioManager			= (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
	}
	
	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
		// mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		KENLog.e("ken", "onCallStateChanged-state: " + state);
		KENLog.e("ken", "onCallStateChanged-incomingNumber: " + incomingNumber);
		// 先把狀態存起來
		TemporaryRingMode = mAudioManager.getRingerMode();
		//
		switch (state) {
		case TelephonyManager.CALL_STATE_IDLE:
			// 掛斷後恢復狀態
			KENLog.e("ken", "setRingerMode "+ TemporaryRingMode);
			mAudioManager.setRingerMode(TemporaryRingMode);
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
			// CALL_STATE_OFFHOOK;
			break;
		case TelephonyManager.CALL_STATE_RINGING:
			
			Map<String, String> blackMap = ((CallBlock2)mContext.getApplicationContext()).getBlockNubMap();
			if (incomingNumber.equals("")) incomingNumber = mContext.getResources().getString(R.string.no_number); 
			
			String status = blackMap.get(incomingNumber);
			// 如果沒有再替換成+886找找看
			if (status == null) status = blackMap.get(incomingNumber.replace("+886", "0"));
			
			if (status != null) {
				int s = 0;
				try {
					s = Integer.valueOf(status);
				} catch (Exception e) { }
				// 拒接
				if (s == RINGER_MODE_EndCall) {
					endCall();
					showNotification(incomingNumber);
				}
				// 靜音
				if (s == RINGER_MODE_Silent) {
					mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
				}
				// 震動
				if (s == RINGER_MODE_Vibrate) {
					mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
				}
			}
			
			break;
		default:
			break;
		}
		super.onCallStateChanged(state, incomingNumber);
	}

	@Override
	public void onDataConnectionStateChanged(int state) {
		KENLog.v(this.getClass().getName(), "onDataConnectionStateChanged-state: " + state);
		super.onDataConnectionStateChanged(state);
	}

	@Override
	public void onDataConnectionStateChanged(int state, int networkType) {
		KENLog.v(this.getClass().getName(), "onDataConnectionStateChanged-state: " + state);
		KENLog.v(this.getClass().getName(), "onDataConnectionStateChanged-networkType: " + networkType);
		super.onDataConnectionStateChanged(state, networkType);
	}

	@Override
	public void onServiceStateChanged(ServiceState serviceState) {
		KENLog.v(this.getClass().getName(), "onServiceStateChanged-ServiceState: " + serviceState);
		super.onServiceStateChanged(serviceState);
	}

	@Override
	public void onSignalStrengthChanged(int asu) {
		KENLog.v(this.getClass().getName(), "onSignalStrengthChanged-asu: " + asu);
		super.onSignalStrengthChanged(asu);
	}

	@Override
	public void onSignalStrengthsChanged(SignalStrength signalStrength) {
		KENLog.v(this.getClass().getName(), "onSignalStrengthsChanged-signalStrength: " + signalStrength);
		super.onSignalStrengthsChanged(signalStrength);
	}

	/**
	 * 利用JAVA反射机制调用ITelephony的endCall()结束通话。
	 */
	private void endCall() {
		// 初始化iTelephony
		Class<TelephonyManager> c = TelephonyManager.class;
		Method getITelephonyMethod = null;
		try {
			// 获取所有public/private/protected/默认
			// 方法的函数，如果只需要获取public方法，则可以调用getMethod.
			getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
			// 将要执行的方法对象设置是否进行访问检查，也就是说对于public/private/protected/默认
			// 我们是否能够访问。值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false
			// 则指示反射的对象应该实施 Java 语言访问检查。
			getITelephonyMethod.setAccessible(true);
			ITelephony iTelephony = (ITelephony) getITelephonyMethod.invoke(mTelephonyManager, (Object[]) null);
			iTelephony.endCall();
			KENLog.v(this.getClass().getName(), "endCall......");
		} catch (Exception e) {
			KENLog.e(this.getClass().getName(), "endCallError:"+ e.getMessage());
		}
	}

	private void showNotification(String number){
//		int icon = R.drawable.ic_action_search;
//		long when = System.currentTimeMillis();
//		Notification notification = new Notification(icon, "CallBolck", when);
//		notification.flags = Notification.FLAG_AUTO_CANCEL;
//		notification.defaults = Notification.DEFAULT_SOUND;
//		notification.setLatestEventInfo(mContext, "拒接來電", number+" ", null);
//		mNotificationManager.notify(0, notification);
		if (number.equals("")) number = mContext.getResources().getString(R.string.no_number);
		// 宣告圖示
		int icon = R.drawable.ic_launcher;
		// 通知標題
		CharSequence tickerText = "CallBolck";
		long when = System.currentTimeMillis();
		CharSequence contentTitle = "拒接來電";
		// 取得通知內容
		CharSequence contentText = Helper.getDateTime("yyyy/MM/dd hh:mm:ss") + " " + number;
		// 點選通知後跳出的activity
		Intent notificationIntent = new Intent(mContext, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
		Notification notification = new Notification(icon, tickerText, when);
		// 點選後自動移除該通知
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.defaults = Notification.DEFAULT_SOUND;
		notification.setLatestEventInfo(mContext, contentTitle, contentText, contentIntent);
		mNotificationManager.notify(0, notification);
	}
	
}
